<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validate-trigger="submit" err-show-type="toast" :label-width="100">
			<uni-forms-item name="order_id" label="订单 id" required>
				<uni-easyinput placeholder="分类 id，参考`orders`表" disabled v-model="formData.order_id"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="product_code" label="货品编码" required>
				<uni-easyinput placeholder="货品编码" disabled v-model="formData.product_code"></uni-easyinput>
				<button style="font-size: 14px;" @click="openProductSelector">选择货品</button>
			</uni-forms-item>
			<uni-forms-item name="product_name" label="货品名称" required>
				<uni-easyinput placeholder="货品名称" disabled v-model="formData.product_name"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item name="specification" label="规格" required>
				<uni-easyinput placeholder="规格" disabled v-model="formData.specification"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="unit" label="单位" required>
				<uni-easyinput placeholder="单位" disabled v-model="formData.unit"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item name="moq" label="MOQ">
				<uni-easyinput type="number" placeholder="MOQ" v-model="formData.moq"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item name="position" label="货位">
				<uni-easyinput placeholder="货位" v-model="formData.position"></uni-easyinput>
			</uni-forms-item>

			<!-- 	<uni-forms-item name="quantity_sold" label="已销售数量">
				<uni-easyinput type="number" placeholder="已销售数量" v-model="formData.quantity_sold"></uni-easyinput>
			</uni-forms-item> -->
			<uni-forms-item name="gift" label="是否赠品">
				<switch @change="binddata('gift', $event.detail.value)" :checked="formData.gift"></switch>
			</uni-forms-item>
			<uni-forms-item name="delivery_date" label="发货日期">
				<uni-datetime-picker type="type" return-type="timestamp" v-model="formData.delivery_date"
					placeholder="发货日期"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="order_line_number" label="订单行号">
				<uni-easyinput placeholder="订单行号" v-model="formData.order_line_number"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="internal_special_note" label="内部特殊备注">
				<uni-easyinput placeholder="内部特殊备注" v-model="formData.internal_special_note"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="supplier_PN" label="原供应商PN/misumi料号">
				<uni-easyinput placeholder="原供应商PN/misumi料号" v-model="formData.supplier_PN"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="goods_desc" label="产品中文描述">
				<uni-easyinput placeholder="产品中文描述" v-model="formData.goods_desc"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="version" label="版本号PC">
				<uni-easyinput placeholder="版本号PC" v-model="formData.version"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="cleaning_type" label="清洗类型">
				<uni-easyinput placeholder="清洗类型" v-model="formData.cleaning_type"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="qx_price" label="清洗单价">
				<uni-easyinput type="number" placeholder="清洗单价" v-model="formData.qx_price"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="unit_price_excl_tax" label="未税单价">
				<uni-easyinput type="number" placeholder="未税单价" v-model="formData.unit_price_excl_tax"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="price_excl_tax" label="未税价">
				<uni-easyinput type="number" placeholder="未税价" v-model="formData.price_excl_tax"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="tax_rate" label="税率">
				<uni-easyinput type="number" placeholder="税率" v-model="formData.tax_rate"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="tax_amount" label="税额">
				<uni-easyinput type="number" placeholder="税额" v-model="formData.tax_amount"></uni-easyinput>
			</uni-forms-item>

			<uni-forms-item name="quantity" label="数量" required>
				<uni-easyinput type="number" required placeholder="数量" @input="quantityInput"
					v-model="formData.quantity"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="amount" label="销售金额" required>
				<uni-easyinput type="number" required placeholder="销售金额" v-model="formData.amount"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="additional_items" label="备注">
				<uni-easyinput placeholder="备注" v-model="formData.additional_items"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="status" label="订单详情状态">
				<uni-data-checkbox v-model="formData.status" :localdata="status_localdata"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item name="kp_num" label="发票号">
				<uni-easyinput placeholder="发票号" v-model="formData.kp_num"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="kp_date" label="开票日期">
				<uni-datetime-picker type="type" return-type="timestamp" v-model="formData.kp_date"
					placeholder="开票日期"></uni-datetime-picker>
			</uni-forms-item>

			<uni-forms-item name="is_kp" label="是否开票">
				<switch @change="binddata('is_kp', $event.detail.value)" :checked="formData.is_kp"></switch>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" @click="submit">提交</button>
			</view>
			<!-- 选择货品弹窗 -->
			<uni-popup ref="popup" type="dialog" :mask-click="false">
				<view class="popup-content">
					<!-- 搜索框 -->
					<uni-easyinput placeholder="搜索货品" v-model="searchQuery" @input="filterProducts"></uni-easyinput>
					<!-- 货品列表 -->
					<view class="popup-content-b">
						<view class="popup-content-list" v-for="(product, index) in filteredProducts" :key="index"
							@click="selectProduct(product)">
							<text>{{ product.goods_sn }}</text>
							<text style="margin-left: 10px; color: red;">{{ product.remain_count }}</text>
						</view>

					</view>
					<view class="t-c mar-t-15 ">
						<button class="mini-btn" @click="close" type="default" size="mini">确定</button>
					</view>
				</view>

			</uni-popup>
		</uni-forms>

	</view>
</template>

<script>
	let debounceTimer = null;
	import {
		validator
	} from '../../js_sdk/validator/order-text.js';

	const db = uniCloud.database();
	const dbCollectionName = 'order-text';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"kp_num": null,
				"kp_date": null,
				"is_kp": null,
				"status": 0,
				"order_id": "",
				"product_code": "",
				"product_name": "",
				"specification": "",
				"unit": "",
				"huoping_id": "",
				"quantity": 0,
				"qx_price": 0,
				"moq": null,
				"unit_price_excl_tax": null,
				"tax_rate": 0.13,
				"tax_amount": null,
				"amount": null,
				"quantity_sold": null,
				"gift": null,
				"delivery_date": null,
				"order_line_number": "",
				"internal_special_note": "",
				"supplier_PN": "",
				"goods_desc": "",
				"version": "",
				"cleaning_type": "",
				"qx_price": null,
				"price_excl_tax": null,
				"additional_items": "",
				"position": ""
			}
			return {
				formData,
				status_localdata: [{
						"text": "配货",
						"value": 0
					},
					{
						"text": "清洗中",
						"value": 1
					},
					{
						"text": "已发",
						"value": 2
					},
					{
						"text": "终止",
						"value": 3
					}
				],
				remain_count: 0, //库存数量
				searchQuery: '', // 搜索框输入内容
				selectedCategory: 0, // 当前选择的类别
				categories: ['全部', '类别1', '类别2'], // 货品类别
				products: [ // 假设有很多货品
				],
				filteredProducts: [], // 筛选后的货品列表
				paginatedProducts: [], // 分页后的货品列表
				currentPage: 1, // 当前页码
				itemsPerPage: 10, // 每页显示数量
				hasMore: true,
				formOptions: {},
				id: '',
				item: {},
				old: {},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		async onLoad(e) {
			this.formData.order_id = e.order_id
			this.formDataId = e.id;
			if (e.id) {
				this.getDetail(e.id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
			this.getInventory()

		},
		methods: {
			getOld(id) {
				db.collection("opendb-mall-goods").where({
					_id: id
				}).get().then((res) => {
					const data = res.result.data[0]
					if (data) {
						this.item = data
						this.remain_count = this.item.remain_count
						console.log(this.item);
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).where({
					_id: id
				}).get().then((res) => {
					const data = res.result.data[0]
					if (data) {
						this.formData = data
						this.old = {
							...data
						}
						this.getOld(this.old.huoping_id)
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			},
			//数量修改
			quantityInput(e) {

				// 如果定时器存在，清除上次的定时器
				if (debounceTimer) {
					clearTimeout(debounceTimer);
				}
				// 设置新的定时器，在1000毫秒后执行函数
				debounceTimer = setTimeout(() => {
					console.log(this.remain_count, this.item.quantity, this.item);
					// 执行逻辑
					if (e > this.remain_count) {
						this.$set(this.formData, 'quantity', 0); // 确保是响应式更新
						console.log(this.formData.quantity);
						uni.showToast({
							title: '库存还有' + this.remain_count,
							duration: 2000,
							icon: 'none'
						});
					}
					console.log(this.item, this.formDat);
					console.log(this.item.price, this.formData.quantity);
					this.formData.price_excl_tax = this.formData.unit_price_excl_tax * this.formData
						.quantity //未税价格
					this.formData.tax_amount = this.formData.price_excl_tax * 0.13 //税率
					this.formData.amount = this.formData.price_excl_tax + this.formData.tax_amount //销售金额
				}, 1000); // 这里是防抖的延迟时间，1000毫秒（1秒）

			},
			close() {
				this.$refs.popup.close()
			},
			openProductSelector() {
				this.isProductPopupVisible = true;
				this.filterProducts(); // 初始化筛选
			},
			filterProducts() {
				let products = this.products;
				console.log(this.products);
				// 先根据搜索框过滤
				if (this.searchQuery) {
					products = products.filter(product => product.goods_sn
						.includes(this.searchQuery));
				}

				// 然后根据选择的类别进行过滤
				if (this.selectedCategory > 0) {
					products = products.filter(product => product.category === this.categories[this.selectedCategory]);
				}

				this.filteredProducts = products;
				this.paginateProducts(); // 分页
			},
			filterByCategory() {
				this.filterProducts(); // 筛选时按类别过滤
			},
			paginateProducts() {
				const start = (this.currentPage - 1) * this.itemsPerPage;
				const end = this.currentPage * this.itemsPerPage;
				this.paginatedProducts = this.filteredProducts.slice(start, end);
				this.hasMore = this.filteredProducts.length > end; // 判断是否还有更多数据
			},
			loadMore() {
				this.currentPage += 1;
				this.paginateProducts(); // 加载更多
			},
			selectProduct(product) {
				console.log(product, '货品数据');
				this.formData.product_name = product.name;
				this.formData.product_code = product.goods_sn;
				this.formData.goods_desc = product.goods_desc
				this.formData.qx_price = product.qx_price
				this.formData.moq = product.moq
				this.formData.specification = product.type;
				this.formData.unit = product.danwei;
				this.remain_count = product.remain_count
				this.formData.huoping_id = product._id
				this.formData.cleaning_type = product.qx_type
				this.formData.unit_price_excl_tax = product.shop_price
				console.log(product.position);
				this.formData.position = product.position
				this.item = product
				console.log("this.formData: " + JSON.stringify(this.formData));
				this.isProductPopupVisible = false;
			},
			openProductSelector() {
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('center')
			},

			//获取库存商品
			async getInventory() {
				let products = []
				let offset = 0
				const batchSize = 1000

				while (true) {
					const result = await db.collection('opendb-mall-goods')
						.orderBy('add_date', 'desc')
						.skip(offset)
						.limit(batchSize)
						.get()
					console.log(res);
					const res = result.result
					if (!res.data.length) break

					products = products.concat(res.data)
					offset += batchSize
				}
				this.products = products
			},
			//修改库存数量
			async updateKucun(type, num, id) {
				let ws = (this.formData.unit_price_excl_tax * num) * 0.13 + this.formData.unit_price_excl_tax *
					num //未税价格
				console.log(ws);
				let data = {
					id, // 替换为你要更新库存的商品的 ID
					quantity: num * 1, // 传入你要增加的库存数量
					type, //增加或者修改
					order_id: this.formData.order_id,
					sale_price: ws

				}
				console.log(data);
				uniCloud.callFunction({
					name: 'update-kucun',
					data
				}).then(res => {
					console.log(res);
					if (res.result.code === 200) {
						console.log('库存更新成功');
					} else {
						console.log('库存更新失败:', res.result.msg);
					}
				}).catch(err => {
					console.error('调用云函数失败', err);
				});
			},
			/**
			 * 验证表单并提交
			 */
			submit() {

				if (this.formData.quantity <= 0) {
					uni.showToast({
						title: "数量不对",
						icon: 'none'
					})
					return false
				}
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				console.log(this.formDataId);
				if (this.formDataId) {

					if (this.old.huoping_id != this.formData.huoping_id) {
						this.updateKucun(2, Math.abs(this.old.quantity), this.old.huoping_id)
						this.updateKucun(1, Math.abs(this.formData.quantity), this.formData.huoping_id)
					}

					if (this.old.huoping_id == this.formData.huoping_id) {
						console.log('两次ID一样', this.formData.quantity, this.old.quantity);

						if (this.formData.quantity != this.old.quantity) {
							//如果现在的数量大于原来的数量
							let num = this.formData.quantity - this.old.quantity
							if (num > 0) {
								this.updateKucun(1, Math.abs(num), this.old.huoping_id)
							} else if (num < 0) {

								this.updateKucun(2, Math.abs(num), this.old.huoping_id)
							}
						}

					}
					// 使用 clientDB 提交数据
					return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
						uni.showToast({
							icon: 'none',
							title: '修改成功'
						})
						this.getOpenerEventChannel().emit('refreshData')
						setTimeout(() => uni.navigateBack(), 500)
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
				} else {
					value.huoping_id = this.formData.huoping_id
					console.log(value);
					this.updateKucun(1, this.formData.quantity, this.formData.huoping_id)
					// 使用 clientDB 提交数据
					return db.collection(dbCollectionName).add(value).then((res) => {
						uni.showToast({
							icon: 'none',
							title: '新增成功'
						})
						this.getOpenerEventChannel().emit('refreshData')
						setTimeout(() => uni.navigateBack(), 500)
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
				}

			}
		}
	}
</script>

<style>
	.uni-container {
		padding: 15px;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;

	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 50px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
	}

	.uni-button {
		width: 184px;
	}

	.popup-content {
		background-color: #fff;
		width: 500px;
		height: 400px;
		padding: 15px;
	}

	.popup-content-b {
		height: calc(100% - 80px);
		overflow: auto;
		overflow-x: hidden;
	}

	.popup-content-list {
		border-top: 1px solid #ddd;
		/* 边框颜色为浅灰色 */
		padding: 8px 18px;
		/* 稍微增加内边距 */
		cursor: pointer;
		display: flex;
		justify-content: space-between;
		align-items: center;
		/* 保证文字在垂直方向居中 */
		transition: all 0.3s ease;
		/* 添加过渡效果，使hover时变得更平滑 */
		border-radius: 8px;
		/* 圆角效果 */
		background-color: #f9f9f9;
		/* 初始背景色为浅灰色 */
		margin-bottom: 2px;
	}

	.popup-content-list:hover {
		opacity: 0.8;
		/* 提高透明度，增加悬停的立体感 */
		background-color: #f1f1f1;
		/* 浅灰色背景色 */
		color: #333;
		/* 悬停时文本颜色变为深灰色 */
		border-top: 1px solid #aaa;
		/* 增加更明显的边框颜色 */
		box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
		/* 添加阴影效果，使元素浮动 */
		transform: scale(1.02);
		/* 鼠标悬停时微微放大，增加交互感 */
	}
</style>